import { isArray, isString, _pick } from "mmb";
import { AppCTX } from "../../types/koaExtend";
import { createBrandApiMWRouter } from "../../middleware/brand-api/brandAdminChecker"
import pageMW from "../../middleware/pager";
import { upsertProductGroup, removeProductGroup, updateProductGroupName, reorderProductGroups, listNormalProductGroupsByBrandID } from "../../service/productGroupService"

const router = createBrandApiMWRouter();

// 获取品牌商品分组列表
router.get('brand-productGroups', '/brd/:brandId/productGroups', pageMW, async(ctx: AppCTX, next) => {
  const { brandId } = ctx.params;
  const {userId, limit, offset} = ctx
  
  const {
    total,
    items,
  } = await listNormalProductGroupsByBrandID(
    brandId,
    { limit, offset }
  );

  ctx.body = {
    total,
    rows: items.map((it) => ({
      ..._pick(
        it,
        "productGroupId",
        "name",
        "productCount",
      ),
    })),
  };
})

// 新增品牌商品分组
router.post("/brd/:brandId/productGroup", async (ctx: AppCTX, next) => {
  const { brandId } = ctx.params;
  const { name } = ctx.request.body;
  const { userId } = ctx;

  const productGroup = await upsertProductGroup({
    brandId,
    name,
  });

  ctx.body = {
    ..._pick(
      productGroup,
      "productGroupId",
      "sortNo",
      "name",
      "productCount",
    ),
  };
});

// 移除品牌商品分组
router.delete("/brd/:brandId/productGroup/:productGroupId", async (ctx: AppCTX, next) => {
  const { brandId, productGroupId } = ctx.params;
  const { userId } = ctx;
  const productGroup = await removeProductGroup({
    productGroupId
  })
  ctx.body = {
    ..._pick(
      productGroup,
      "productGroupId",
      "sortNo",
      "name",
      "productCount",
    ),
  };
});

// 更新品牌商品分组
router.put("/brd/:brandId/productGroup/:productGroupId", async (ctx: AppCTX, next) => {
  const { brandId, productGroupId } = ctx.params;
  const { name } = ctx.request.body;
  const { userId } = ctx;

  const productGroup = await updateProductGroupName({
    productGroupId,
    name,
  });

  //2 根据sync_id发送异步消息给商品分组系统
  ctx.body = {
    ..._pick(
      productGroup,
      "productGroupId",
      "sortNo",
      "name",
      "productCount",
    ),
  };
});

// 重排分组顺序 
router.post("/brd/:brandId/productGroup/reorder", async (ctx: AppCTX, next) => {
  const { brandId } = ctx.params;
  const { productGroupIds } = ctx.request.body;
  const { userId } = ctx;

  if (!isArray(productGroupIds)) {
    ctx.throw(400, "productGroupIds is valid")
  } else {
    if (productGroupIds.length === 0) {
      ctx.throw(400, "productGroupIds is empty")
    }
    if (!productGroupIds.every(id => isString(id))) {
      ctx.throw(400, "not every productGroupId is valid")
    }
  }

  const total = await reorderProductGroups(productGroupIds)
  
  ctx.body = {
    total
  };
});

export default router;
